﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using Crm2011.Framework.Core;



namespace ScriptEase
{
    /// <summary>
    /// The <c>StaticMap</c> gets the local file mapping from a mapping file.
    /// </summary>
    internal class StaticMap : IWorkspaceMapper
    {
        public StaticMap(string staticMappingFileFullPath, string baseDirectory)
        {
            _staticMappingFileFullPath = staticMappingFileFullPath;
            _baseDirectory = baseDirectory;
        }



        private Workspace _workspace;
        private string _staticMappingFileFullPath;
        private LocalWorkspace _workspaceMap;
        private readonly string _baseDirectory;



        public void Initialize(Workspace workspace)
        {
            if (_staticMappingFileFullPath == null) return;
            if (!File.Exists(_staticMappingFileFullPath))
            {
                Trace.Default.Error("Static mapping file is configured but it was not found!");
                _staticMappingFileFullPath = null;
            }
            _workspace = workspace;
        }



        string IWorkspaceMapper.GetFilePath(WebResource webResource)
        {
            if (_staticMappingFileFullPath == null) return null;

            // Lazy initialization
            if (_workspaceMap == null)
            {
                initialize();
                if (_workspaceMap == null) return null;
            }


            var staticMapping = _workspaceMap.Mappings.FirstOrDefault(item => item.WebResourceName.Equals(webResource.Name, StringComparison.InvariantCultureIgnoreCase));

            return staticMapping == null ? null
                : Workspace.GetFullPath(staticMapping.LocalFileName, _baseDirectory);
        }



        private void initialize()
        {
            try
            {
                Trace.Default.Info("Reading static mappings from {0}", _staticMappingFileFullPath);
                string configFileContent = File.ReadAllText(_staticMappingFileFullPath, Encoding.UTF8);
                //_workspaceMap = new LocalWorkspace();
                //_workspaceMap.Mappings = new List<WorkspaceMapping>();
                //_workspaceMap.Mappings.Add(new WorkspaceMapping{ LocalFileName = "abc", WebResourceName = "def"});
                //_workspaceMap.Mappings.Add(new WorkspaceMapping{ LocalFileName = "abc", WebResourceName = "def"});
                //var x = SerializationHelper.SerializeDc(_workspaceMap);
                _workspaceMap = SerializationHelper.DeserializeDc<LocalWorkspace>(configFileContent);
            }
            catch (Exception exception)
            {
                Trace.Default.LogException(exception);
                _workspaceMap = null;
            }
        }
    }
}